package bitsetdemo;

import java.util.Arrays;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-10-17
 * Time:21:05
 */
public class MyBitSet {
    public byte[] elem;
    public int usedSize;

    public MyBitSet() {
        this.elem = new byte[1];
    }

    /**
     *
     * @param n 多少位
     */
    public MyBitSet(int n) {
        this.elem = new byte[n/8+1];
    }

    /**
     * 设置某一位为 1
     * @param val
     */
    public void set(int val) {
        if (val < 0) {
            throw  new IndexOutOfBoundsException();
        }
        int arrayIndex = val / 8;
        //扩容
        if (arrayIndex > elem.length + 1) {
            elem = Arrays.copyOf(elem, arrayIndex + 1);
        }
        int bitIndex = val % 8;
        elem[arrayIndex] |= (1 << bitIndex);
        usedSize++;
    }

    /**
     * 判断当前位是否为 1
     * @param val
     * @return
     */
    public boolean get(int val) {
        if (val < 0) {
            throw new IndexOutOfBoundsException();
        }
        int arrayIndex = val / 8;
        int bitIndex = val % 8;
        if ((elem[arrayIndex] & (1 << bitIndex)) != 0) {
            return true;
        }
        return false;
    }

    /**
     * 将当前位置为 0
     * @param val
     */
    public void reSet(int val) {
        if (val < 0) {
            throw new IndexOutOfBoundsException();
        }
        int arrayIndex = val / 8;
        int bitIndex = val % 8;
        elem[arrayIndex] &= ~(1 << bitIndex);
        usedSize--;
    }

    public int getUsedSize() {
        return usedSize;
    }
}
